package com.lovefreedom.psi.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.lovefreedom.psi.bean.Category;
import com.lovefreedom.psi.dao.CategoryDao;
import com.lovefreedom.psi.dao.impl.CategoryDaoImpl;

public class CategoryAction {
	private int id;
	private String name;
	private String sort;
	private int parentId;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getParentId() {
		return parentId;
	}

	public void setParentId(int parentId) {
		this.parentId = parentId;
	}

	public String list() throws Exception {
		System.out.println("执行列表操作");

		// 如果没有货品分类，初始化货品分类
		CategoryDao dao = new CategoryDaoImpl();
		List list = dao.getCategoryList();
		if (list.size() == 0) {
			Category category = new Category();
			category.setName("货品分类");
			category.setId(1);
			category.setParentId(0);
			category.setSort("50");
			category.setLevel(1);
			dao.addCategory(category);
		}
		// 获取货品分类树
		List categoryTree = dao.getCategoryTree();
		// 将货品分类树传到页面
		HttpServletRequest req = ServletActionContext.getRequest();
		req.setAttribute("categoryTree", categoryTree);
		return "list";
	}

	public String add() throws Exception {
		System.out.println("执行增加操作");
		CategoryDao dao = new CategoryDaoImpl();
		Category category = new Category();
		Category parent = new Category();
		parent = dao.findCategoryById(parentId);
		category.setName(name);
		category.setParentId(parentId);
		category.setLevel(parent.getLevel() + 1);
		dao.addCategory(category);
		return "list";
	}

	public String delete() throws Exception {

		System.out.println("执行删除操作");
		HttpServletRequest req = ServletActionContext.getRequest();
		String categoryIds[] = req.getParameterValues("categoryIds");

		CategoryDao dao = new CategoryDaoImpl();

		for (int i = 0; i < categoryIds.length; i++) {
			int id = Integer.parseInt(categoryIds[i]);
			List list = dao.getCategoryChildren(id);
			// 没有子目录并且不为根的目录才能被删除
			if (list.size() == 0 && id != 1) {
				dao.deleteCategory(id);
			}
		}
		return "list";
	}

	public String update() throws Exception {

		System.out.println("执行修改操作");

		CategoryDao dao = new CategoryDaoImpl();
		Category category = new Category();
		Category parent = new Category();
		parent = dao.findCategoryById(parentId);

		category.setId(id);
		category.setName(name);
		category.setParentId(parentId);
		category.setLevel(parent.getLevel() + 1);

		dao.updateCategory(category);
		return "list";
	}
}
